import React, { useState, useEffect, useCallback } from 'react';
import {
  Dialog,
  DialogContent,
  Box,
  Typography,
  IconButton,
  Avatar,
  Chip,
  Button,
  TextField,
  Divider,
  CircularProgress,
  Alert,
  ImageList,
  ImageListItem,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  ListItemSecondaryAction,
  Pagination,
  Paper,
  Skeleton,
} from '@mui/material';
import {
  Close,
  Favorite,
  FavoriteBorder,
  Comment as CommentIcon,
  Send,
  PlayArrow,
  Image as ImageIcon,
  Person,
  MoreVert,
} from '@mui/icons-material';
import { ContentDetail, ContentType, TargetType, CommentOrderBy, type Comment } from '../../../types';
import { useContent, useInteraction } from '../../../hooks';
import { ImageCarousel } from '../../../components';

interface ContentModalProps {
  open: boolean;
  contentId: number | null;
  onClose: () => void;
  onLike?: (contentId: number) => void;
}

const ContentModal: React.FC<ContentModalProps> = ({
  open,
  contentId,
  onClose,
  onLike,
}) => {
  const [content, setContent] = useState<ContentDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [commentText, setCommentText] = useState('');
  const [submittingComment, setSubmittingComment] = useState(false);
  
  // 评论相关状态
  const [comments, setComments] = useState<Comment[]>([]);
  const [commentsLoading, setCommentsLoading] = useState(false);
  const [commentsError, setCommentsError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalComments, setTotalComments] = useState(0);
  const pageSize = 10;

  const { viewContent } = useContent();
  const { toggleLike, createComment, getComments } = useInteraction();

  // 加载评论列表
  const loadComments = useCallback(async (page: number) => {
    if (!contentId) return;

    setCommentsLoading(true);
    setCommentsError(null);
    
    try {
      const response = await getComments({
        contentId,
        page,
        size: pageSize,
        orderBy: CommentOrderBy.CREATED_AT,
      });

      // 处理不同的响应格式
      let commentsData;
      if ((response as any).code === 200) {
        commentsData = (response as any).data;
      } else if ((response as any).comments) {
        commentsData = response;
      } else {
        throw new Error('评论数据格式错误');
      }

      setComments(commentsData.comments || []);
      setTotalPages(commentsData.totalPages || 1);
      setTotalComments(commentsData.total || 0);
      setCurrentPage(page);
    } catch (err) {
      setCommentsError('加载评论失败');
      console.error('加载评论失败:', err);
    } finally {
      setCommentsLoading(false);
    }
  }, [contentId, getComments]);

  const loadContentDetail = async () => {
    if (!contentId) return;

    setLoading(true);
    setError(null);
    
    try {
      const response = await viewContent(contentId);
      // 处理不同的响应格式
      if ((response as any).code === 200) {
        setContent((response as any).data);
      } else if ((response as any).id) {
        // 直接返回数据的情况
        setContent(response as ContentDetail);
      } else {
        setError((response as any).message || '加载内容详情失败');
      }
    } catch (err) {
      setError('加载内容详情失败');
      console.error('加载内容详情失败:', err);
    } finally {
      setLoading(false);
    }
  };

  // 加载内容详情和评论
  useEffect(() => {
    if (open && contentId) {
      loadContentDetail();
      loadComments(1);
    }
  }, [open, contentId, loadComments]);

  // 处理点赞内容
  const handleLike = async () => {
    if (!content) return;

    try {
      await toggleLike({ targetId: content.id, targetType: TargetType.CONTENT });
      // 更新本地状态
      setContent(prev => prev ? {
        ...prev,
        isLiked: !prev.isLiked,
        likeCount: prev.isLiked ? prev.likeCount - 1 : prev.likeCount + 1,
      } : null);
      
      // 通知父组件更新
      if (onLike) {
        onLike(content.id);
      }
    } catch (err) {
      console.error('点赞失败:', err);
    }
  };

  // 处理点赞评论
  const handleCommentLike = async (commentId: number) => {
    try {
      await toggleLike({ targetId: commentId, targetType: TargetType.COMMENT });
      // 更新评论点赞状态
      setComments(prev => prev.map(comment => 
        comment.id === commentId 
          ? {
              ...comment,
              isLiked: !comment.isLiked,
              likeCount: comment.isLiked ? comment.likeCount - 1 : comment.likeCount + 1,
            }
          : comment
      ));
    } catch (err) {
      console.error('评论点赞失败:', err);
    }
  };

  // 处理评论提交
  const handleCommentSubmit = async () => {
    if (!content || !commentText.trim()) return;

    setSubmittingComment(true);
    
    try {
      await createComment({
        contentId: content.id,
        commentText: commentText.trim(),
      });
      
      setCommentText('');
      // 更新评论数量
      setContent(prev => prev ? {
        ...prev,
        commentCount: prev.commentCount + 1,
      } : null);
      
      // 重新加载评论列表
      loadComments(1);
      setCurrentPage(1);
    } catch (err) {
      console.error('评论失败:', err);
    } finally {
      setSubmittingComment(false);
    }
  };

  // 处理分页变化
  const handlePageChange = (event: React.ChangeEvent<unknown>, page: number) => {
    loadComments(page);
  };

  // 处理关闭
  const handleClose = () => {
    setContent(null);
    setError(null);
    setCommentText('');
    setComments([]);
    setCurrentPage(1);
    setTotalPages(1);
    setTotalComments(0);
    setCommentsError(null);
    onClose();
  };

  // 格式化时间
  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 30) return `${days}天前`;
    
    return date.toLocaleDateString('zh-CN');
  };

  if (!open) return null;

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="lg"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: 2,
          maxHeight: '90vh',
          height: '80vh',
        },
      }}
    >
      {/* 关闭按钮 */}
      <IconButton
        onClick={handleClose}
        sx={{
          position: 'absolute',
          right: 8,
          top: 8,
          zIndex: 1,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          color: 'white',
          '&:hover': {
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
          },
        }}
      >
        <Close />
      </IconButton>

      <DialogContent sx={{ p: 0, display: 'flex', height: '100%' }}>
        {loading && (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              width: '100%',
              py: 8,
            }}
          >
            <CircularProgress />
          </Box>
        )}

        {error && (
          <Box sx={{ p: 3, width: '100%' }}>
            <Alert severity="error">{error}</Alert>
          </Box>
        )}

        {content && (
          <Box sx={{ display: 'flex', width: '100%', height: '100%' }}>
            {/* 左侧：媒体内容区域 */}
            <Box sx={{ flex: '1 1 60%', backgroundColor: 'black', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {content.contentType === ContentType.IMAGE ? (
                // 图片轮播：将封面和内容图片合并显示
                (() => {
                  const allImages: string[] = [];
                  
                  // 如果有封面，将封面作为第一张图片
                  if (content.coverUrl) {
                    allImages.push(content.coverUrl);
                  }
                  
                  // 添加内容图片，但避免重复（如果封面和第一张内容图片相同）
                  if (content.images && content.images.length > 0) {
                    content.images.forEach(image => {
                      if (!allImages.includes(image.imageUrl)) {
                        allImages.push(image.imageUrl);
                      }
                    });
                  }
                  
                  return allImages.length > 0 ? (
                    <ImageCarousel
                      images={allImages}
                      alt={content.title}
                      height="100%"
                      width="100%"
                      objectFit="contain"
                      showIndicators={true}
                      showNavigation={true}
                    />
                  ) : (
                    // 无图片时的占位符
                    <Box sx={{ textAlign: 'center', color: 'grey.500' }}>
                      <ImageIcon sx={{ fontSize: 64, mb: 2 }} />
                      <Typography>暂无图片</Typography>
                    </Box>
                  );
                })()
              ) : (
                // 视频内容
                <Box sx={{ maxWidth: '100%', maxHeight: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {content.videos && content.videos.length > 0 ? (
                    <video
                      controls
                      style={{
                        maxWidth: '100%',
                        maxHeight: '100%',
                      }}
                    >
                      <source src={content.videos[0].videoUrl} type="video/mp4" />
                      您的浏览器不支持视频播放
                    </video>
                  ) : content.coverUrl ? (
                    // 如果没有视频但有封面，显示封面作为预览
                    <Box sx={{ position: 'relative' }}>
                      <img
                        src={content.coverUrl}
                        alt={content.title}
                        style={{
                          maxWidth: '100%',
                          maxHeight: '100%',
                          objectFit: 'contain',
                        }}
                      />
                      <Box
                        sx={{
                          position: 'absolute',
                          top: '50%',
                          left: '50%',
                          transform: 'translate(-50%, -50%)',
                          backgroundColor: 'rgba(0, 0, 0, 0.7)',
                          borderRadius: '50%',
                          p: 2,
                        }}
                      >
                        <PlayArrow sx={{ fontSize: 48, color: 'white' }} />
                      </Box>
                    </Box>
                  ) : (
                    // 无视频时的占位符
                    <Box sx={{ textAlign: 'center', color: 'grey.500' }}>
                      <PlayArrow sx={{ fontSize: 64, mb: 2 }} />
                      <Typography>暂无视频</Typography>
                    </Box>
                  )}
                </Box>
              )}
            </Box>

            {/* 右侧：内容信息和评论区域 */}
            <Box sx={{ flex: '1 1 40%', display: 'flex', flexDirection: 'column', minWidth: 400 }}>
              {/* 内容信息区域 */}
              <Box sx={{ p: 3, borderBottom: '1px solid', borderColor: 'divider' }}>
                {/* 用户信息 */}
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                  <Avatar 
                    src={content.userAvatar} 
                    alt={content.username}
                    sx={{ 
                      mr: 2,
                      width: 48,
                      height: 48,
                    }}
                  >
                    {!content.userAvatar && <Person />}
                  </Avatar>
                  <Box sx={{ flexGrow: 1 }}>
                    <Typography variant="subtitle1" fontWeight={600}>
                      {content.username}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {formatTime(content.createdAt)}
                    </Typography>
                  </Box>
                  <Chip
                    icon={content.contentType === ContentType.VIDEO ? <PlayArrow /> : <ImageIcon />}
                    label={content.contentType === ContentType.VIDEO ? '视频' : '图片'}
                    size="small"
                    variant="outlined"
                  />
                </Box>

                {/* 标题和内容 */}
                <Typography variant="h6" gutterBottom fontWeight={600}>
                  {content.title}
                </Typography>
                <Box sx={{ 
                  maxHeight: 200, 
                  overflow: 'auto',
                  mb: 2,
                  '&::-webkit-scrollbar': {
                    width: '4px',
                  },
                  '&::-webkit-scrollbar-track': {
                    background: '#f1f1f1',
                    borderRadius: '2px',
                  },
                  '&::-webkit-scrollbar-thumb': {
                    background: '#c1c1c1',
                    borderRadius: '2px',
                  },
                  '&::-webkit-scrollbar-thumb:hover': {
                    background: '#a8a8a8',
                  },
                }}>
                  <Typography variant="body1">
                    {content.textContent}
                  </Typography>
                </Box>

                {/* 交互按钮 */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                  <Button
                    startIcon={content.isLiked ? <Favorite /> : <FavoriteBorder />}
                    onClick={handleLike}
                    color={content.isLiked ? 'error' : 'inherit'}
                    sx={{ textTransform: 'none' }}
                  >
                    {content.likeCount}
                  </Button>
                  <Button
                    startIcon={<CommentIcon />}
                    color="inherit"
                    sx={{ textTransform: 'none' }}
                  >
                    {totalComments}
                  </Button>
                </Box>
              </Box>

              {/* 评论区域 */}
              <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                {/* 评论列表 */}
                <Box sx={{ flex: 1, overflow: 'auto', px: 2 }}>
                  {commentsLoading ? (
                    <Box sx={{ p: 2 }}>
                      {[...Array(3)].map((_, index) => (
                        <Box key={index} sx={{ display: 'flex', mb: 2 }}>
                          <Skeleton variant="circular" width={40} height={40} sx={{ mr: 2 }} />
                          <Box sx={{ flex: 1 }}>
                            <Skeleton variant="text" width="30%" />
                            <Skeleton variant="text" width="100%" />
                            <Skeleton variant="text" width="60%" />
                          </Box>
                        </Box>
                      ))}
                    </Box>
                  ) : commentsError ? (
                    <Box sx={{ p: 2 }}>
                      <Alert severity="error">{commentsError}</Alert>
                    </Box>
                  ) : comments.length === 0 ? (
                    <Box sx={{ p: 4, textAlign: 'center' }}>
                      <CommentIcon sx={{ fontSize: 48, color: 'grey.300', mb: 2 }} />
                      <Typography color="text.secondary">
                        还没有评论，快来抢沙发吧！
                      </Typography>
                    </Box>
                  ) : (
                    <List sx={{ py: 1 }}>
                      {comments.map((comment) => (
                        <ListItem key={comment.id} alignItems="flex-start" sx={{ px: 1, py: 1.5 }}>
                          <ListItemAvatar>
                            <Avatar 
                              src={comment.userAvatar}
                              alt={comment.username}
                              sx={{ width: 36, height: 36 }}
                            >
                              {!comment.userAvatar && comment.username[0]?.toUpperCase()}
                            </Avatar>
                          </ListItemAvatar>
                          <ListItemText
                            primary={
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
                                <Typography variant="subtitle2" fontWeight={600}>
                                  {comment.username}
                                </Typography>
                                <Typography variant="caption" color="text.secondary">
                                  {formatTime(comment.createdAt)}
                                </Typography>
                              </Box>
                            }
                            secondary={
                              <Box>
                                <Typography variant="body2" sx={{ mb: 1 }}>
                                  {comment.commentText}
                                </Typography>
                                <Button
                                  size="small"
                                  startIcon={comment.isLiked ? <Favorite /> : <FavoriteBorder />}
                                  onClick={() => handleCommentLike(comment.id)}
                                  color={comment.isLiked ? 'error' : 'inherit'}
                                  sx={{ 
                                    textTransform: 'none',
                                    minWidth: 'auto',
                                    px: 1,
                                    fontSize: '0.75rem',
                                  }}
                                >
                                  {comment.likeCount > 0 && comment.likeCount}
                                </Button>
                              </Box>
                            }
                          />
                        </ListItem>
                      ))}
                    </List>
                  )}
                </Box>

                {/* 分页 */}
                {totalPages > 1 && (
                  <Box sx={{ display: 'flex', justifyContent: 'center', py: 2, borderTop: '1px solid', borderColor: 'divider' }}>
                    <Pagination
                      count={totalPages}
                      page={currentPage}
                      onChange={handlePageChange}
                      size="small"
                      color="primary"
                    />
                  </Box>
                )}

                {/* 评论输入框 */}
                <Paper sx={{ p: 2, borderRadius: 0, borderTop: '1px solid', borderColor: 'divider' }}>
                  <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-end' }}>
                    <TextField
                      fullWidth
                      multiline
                      maxRows={3}
                      placeholder="写下你的评论..."
                      value={commentText}
                      onChange={(e) => setCommentText(e.target.value)}
                      disabled={submittingComment}
                      variant="outlined"
                      size="small"
                      sx={{ 
                        '& .MuiOutlinedInput-root': {
                          borderRadius: 2,
                        }
                      }}
                    />
                    <Button
                      variant="contained"
                      onClick={handleCommentSubmit}
                      disabled={!commentText.trim() || submittingComment}
                      startIcon={submittingComment ? <CircularProgress size={16} /> : <Send />}
                      sx={{
                        textTransform: 'none',
                        minWidth: 80,
                        borderRadius: 2,
                      }}
                    >
                      发送
                    </Button>
                  </Box>
                </Paper>
              </Box>
            </Box>
          </Box>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default ContentModal; 